package com.imyours.webservice.services;

import java.util.List;

import org.hibernate.Session;

import com.imyours.model.team.TeamEntity;
import com.imyours.model.user.UserEntity;
import com.imyours.model.util.HibernateUtil;
import com.imyours.webservice.service.Context;
import com.imyours.webservice.service.ContextService;
import com.imyours.webservice.services.annotation.Service;

@Service(name = "createTeam")
public class CreateTeam extends ContextService {

	public CreateTeam(Context context) {
		super(context);
	}

	public void execute() {
		UserEntity user = getUserEntity();
		if (user != null) {
			TeamEntity te = new TeamEntity();
			String name = context.getParameter().get("name");
//			String order = context.getParameter().get("order");
			if (name != null ) {
				te.setName(name);
				te.setUser(user);
				Session se = HibernateUtil.getSessionFactory().openSession();
				List<TeamEntity> teams = se.createQuery("from TeamEntity where user = ?  order by order desc")
						.setEntity(0, user).list();
				if(teams.size()>0){
					te.setOrder(teams.get(0).getOrder()+1);
				}else{
					te.setOrder(0);
				}
				se.beginTransaction();
				se.save(te);
				se.getTransaction().commit();
				se.close();
				context.putResult("id", te.getId());
				context.putResult("name", te.getName());
				context.putResult("order", te.getOrder());
				context.success();
			}

		}

	}

}
